// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

package org.apache.doris.http.rest;

import io.netty.handler.codec.http.HttpMethod;

import org.apache.doris.common.ConfigBase;
import org.apache.doris.common.DdlException;
import org.apache.doris.http.ActionController;
import org.apache.doris.http.BaseRequest;
import org.apache.doris.http.BaseResponse;
import org.apache.doris.http.IllegalArgException;
import org.apache.doris.mysql.privilege.PrivPredicate;
import org.apache.doris.qe.ConnectContext;

import com.google.common.collect.Maps;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/*
 * used to set fe config
 * eg:
 *  fe_host:http_port/api/_set_config?config_key1=config_value1&config_key2=config_value2&...
 */
public class SetConfigAction extends RestBaseAction {
    private static final Logger LOG = LogManager.getLogger(SetConfigAction.class);

    private static final String PERSIST_PARAM = "persist";
    private static final String RESET_PERSIST = "reset_persist";

    public SetConfigAction(ActionController controller) {
        super(controller);
    }

    public static void registerAction(ActionController controller) throws IllegalArgException {
        SetConfigAction action = new SetConfigAction(controller);
        controller.registerHandler(HttpMethod.GET, "/api/_set_config", action);
    }

    @Override
    protected void executeWithoutPassword(BaseRequest request, BaseResponse response) throws DdlException {
        checkGlobalAuth(ConnectContext.get().getCurrentUserIdentity(), PrivPredicate.ADMIN);

        boolean needPersist = false;
        boolean resetPersist = true;
        Map<String, List<String>> configs = request.getAllParameters();
        if (configs.containsKey(PERSIST_PARAM)) {
            List<String> val = configs.remove(PERSIST_PARAM);
            if (val.size() == 1 && val.get(0).equals("true")) {
                needPersist = true;
            }
        }
        if (configs.containsKey(RESET_PERSIST)) {
            List<String> val = configs.remove(RESET_PERSIST);
            if (val.size() == 1 && val.get(0).equals("false")) {
                resetPersist = false;
            }
        }

        Map<String, String> setConfigs = Maps.newHashMap();
        Map<String, String> errConfigs = Maps.newHashMap();

        LOG.debug("get config from url: {}, need persist: {}", configs, needPersist);

        for (Map.Entry<String, List<String>> config : configs.entrySet()) {
            String confKey = config.getKey();
            List<String> confValue = config.getValue();
            try {
                if (confValue != null && confValue.size() == 1) {
                    ConfigBase.setMutableConfig(confKey, confValue.get(0));
                    setConfigs.put(confKey, confValue.get(0));
                } else {
                    throw new DdlException("conf value size != 1");
                }
            } catch (DdlException e) {
                LOG.warn("failed to set config {}:{}", confKey, confValue, e);
                errConfigs.put(confKey, String.valueOf(confValue));
            }
        }

        String persistMsg = "";
        if (needPersist) {
            try {
                ConfigBase.persistConfig(setConfigs, resetPersist);
                persistMsg = "ok";
            } catch (IOException e) {
                LOG.warn("failed to persist config", e);
                persistMsg = e.getMessage();
            }
        }

        Map<String, Object> resultMap = Maps.newHashMap();
        resultMap.put("set", setConfigs);
        resultMap.put("err", errConfigs);
        resultMap.put("persist", persistMsg);

        // to json response
        String result = "";
        ObjectMapper mapper = new ObjectMapper();
        try {
            result = mapper.writeValueAsString(resultMap);
        } catch (Exception e) {
            //  do nothing
        }

        // send result
        response.setContentType("application/json");
        response.getContent().append(result);
        sendResult(request, response);
    }

    public static void print(String msg) {
        System.out.println(System.currentTimeMillis() + " " + msg);
    }
}
